import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
// import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:mime/mime.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

import '../Model/gm_home_model.dart';
import '../Model/gm_index_model.dart';
// import 'package:xin_heart_app/model/home_model.dart';
// import 'package:xin_heart_app/utils/app_utils.dart';

// ignore: must_be_immutable
class GMChatPage extends StatefulWidget {
  String? title;
  final types.User? chatUser;
  final GMIndexData? indexData;
  final GMHomeData? homeData;
  // final HomeData? data;
  GMChatPage(
      {super.key, this.title, this.chatUser, this.indexData, this.homeData});

  @override
  State<GMChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<GMChatPage> {
  List<String> titles = ['你好！祝福你愿望成真', '嗨！缘分让我们相遇！可以聊聊？', '嗨！希望你每天都有好心情'];

  final List<types.Message> _messages = [];
  final _user = const types.User(
    id: '82091008-a483-4a89-ae75-a22bf8d6f3ac',
  );

  @override
  void initState() {
    super.initState();
    if (widget.title == '官方客服') {
      var user = const types.User(
        id: '10086111',
        firstName: "官方客服",
        imageUrl:
            'https://assets.buyonepet.com/eff8a2a242a25e8e57fb61cd3777f958_120_120.jpg',
      );
      // ignore: unused_local_variable
      final message = types.TextMessage(
          author: user, id: '10086111', text: "你好，有什么可以帮助您的吗？");
      setState(() {
        _addMessage(message);
      });
    } else if (widget.title == '系统通知') {
      var user = const types.User(
        id: '1008611',
        firstName: "系统通知",
        imageUrl:
            'https://assets.buyonepet.com/7b2695f688f7bb698789ea398fcafc16_120_120.jpg',
      );
      // ignore: unused_local_variable
      final message =
          types.TextMessage(author: user, id: '1008611', text: "欢迎你注册TaTa伴");
      setState(() {
        _addMessage(message);
      });
    } else {
      if (widget.indexData != null) {
        var user = types.User(
          id: widget.indexData!.id!,
          firstName: widget.indexData!.circleName!,
          imageUrl: widget.indexData!.coverImage!,
        );

        final message =
            types.TextMessage(author: user, id: widget.indexData!.id!, text: "hi，很高兴见到大家",createdAt: DateTime.now().millisecondsSinceEpoch);
        setState(() {
          _addMessage(message);
        });
      } else if (widget.homeData != null) {
        var user = const types.User(
          id: "82091008-a483-4a89-ae75-a22bf8d6f3ac",
          imageUrl: 'GMUserManager().user!.icon'
        );
        final message = types.TextMessage(
          author: user,
          id: "82091008-a483-4a89-ae75-a22bf8d6f3ac",
          text: "您好，在吗，看到你发布的领养信息，方便了解${widget.homeData!.nick!}更多的信息吗",
          createdAt: DateTime.now().millisecondsSinceEpoch,
        );
        setState(() {
          _addMessage(message);
        });
      }
    }
    _guluMessage();
    // _saveMessageUser();
  }

  void _addMessage(types.Message message) {
    setState(() {
      _messages.insert(0, message);
    });
  }

  void _handleAttachmentPressed() {
    showModalBottomSheet<void>(
        context: context,
        builder: (BuildContext context) {
          return SafeArea(
            child: SizedBox(
              height: 144,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _handleImageSelection();
                    },
                    child: const Align(
                      alignment: AlignmentDirectional.center,
                      child: Text(
                        '图片',
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 15,
                            fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _handleFileSelection();
                    },
                    child: const Align(
                      alignment: AlignmentDirectional.center,
                      child: Text(
                        '文件',
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 15,
                            fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Align(
                      alignment: AlignmentDirectional.center,
                      child: Text(
                        '取消',
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 15,
                            fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        });
  }

  void _handleFileSelection() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.any,
    );

    if (result != null && result.files.single.path != null) {
      final message = types.FileMessage(
        author: _user,
        createdAt: DateTime.now().millisecondsSinceEpoch,
        id: const Uuid().v4(),
        mimeType: lookupMimeType(result.files.single.path!),
        name: result.files.single.name,
        size: result.files.single.size,
        uri: result.files.single.path!,
      );

      _addMessage(message);
    }
  }

  void _handleImageSelection() async {
    final result = await ImagePicker().pickImage(
      imageQuality: 70,
      maxWidth: 1440,
      source: ImageSource.gallery,
    );

    if (result != null) {
      final bytes = await result.readAsBytes();
      final image = await decodeImageFromList(bytes);

      final message = types.ImageMessage(
        author: _user,
        createdAt: DateTime.now().millisecondsSinceEpoch,
        height: image.height.toDouble(),
        id: const Uuid().v4(),
        name: result.name,
        size: bytes.length,
        uri: result.path,
        width: image.width.toDouble(),
      );

      _addMessage(message);
    }
  }

  void _handleMessageTap(BuildContext _, types.Message message) async {
    print('_handleMessageTap');
    if (message is types.FileMessage) {
      var localPath = message.uri;

      if (message.uri.startsWith('http')) {
        try {
          final index =
              _messages.indexWhere((element) => element.id == message.id);
          final updatedMessage =
              (_messages[index] as types.FileMessage).copyWith(
            isLoading: true,
          );

          setState(() {
            _messages[index] = updatedMessage;
          });

          final client = http.Client();
          final request = await client.get(Uri.parse(message.uri));
          final bytes = request.bodyBytes;
          final documentsDir = (await getApplicationDocumentsDirectory()).path;
          localPath = '$documentsDir/${message.name}';

          if (!File(localPath).existsSync()) {
            final file = File(localPath);
            await file.writeAsBytes(bytes);
          }
        } finally {
          final index =
              _messages.indexWhere((element) => element.id == message.id);
          final updatedMessage =
              (_messages[index] as types.FileMessage).copyWith(
            isLoading: null,
          );

          setState(() {
            _messages[index] = updatedMessage;
          });
        }
      }

      await OpenFilex.open(localPath);
    }
  }

  void _handlePreviewDataFetched(
    types.TextMessage message,
    types.PreviewData previewData,
  ) {
    final index = _messages.indexWhere((element) => element.id == message.id);
    final updatedMessage = (_messages[index] as types.TextMessage).copyWith(
      previewData: previewData,
    );

    setState(() {
      _messages[index] = updatedMessage;
    });
  }

  void _handleSendPressed(types.PartialText message) {
    print('12344555');
    final textMessage = types.TextMessage(
      author: _user,
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: const Uuid().v4(),
      text: message.text,
    );

    _addMessage(textMessage);
  }

  void _guluMessage() {
    // HomeData myData = widget.data ?? HomeData();
    // String value = myData.wishContent ?? "";
    // if (value.isNotEmpty) {
    //   String str = "鼓励了你的美愿贴\n${titles[Random().nextInt(titles.length)]}";
    //   widget.data!.wishId = str;
    //   final textMessage = types.TextMessage(
    //     author: _user,
    //     createdAt: DateTime.now().millisecondsSinceEpoch,
    //     id: const Uuid().v4(),
    //     text: str,
    //   );

    //   _addMessage(textMessage);
    // }
  }

  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: GMAppUtil.navText(widget.title!),
        ),
        elevation: 0,
        actions: [
          Visibility(
            visible: (widget.title != '官方客服' && widget.title != '系统通知'),
            child: InkWell(
              onTap: () {
                showBottomSheet(context);
              },
              child: Image.asset(
                "assets/images/gm_xq_gd_btn.png",
                width: 20,
                height: 20,
              ),
            ),
          ),
          const SizedBox(
            width: 12,
          )
        ],
      ),
      body: Chat(
        messages: _messages,
        onAttachmentPressed: _handleAttachmentPressed,
        onMessageTap: _handleMessageTap,
        onPreviewDataFetched: _handlePreviewDataFetched,
        onSendPressed: _handleSendPressed,
        showUserAvatars: true,
        showUserNames: true,
        user: _user,
      ),
    );
  }

  void showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: 200,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.report),
                title: const Text('举报'),
                onTap: () {
                  // 处理举报操作
                  Navigator.pop(context);
                  showiOSAlertDialog(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.block),
                title: const Text('拉黑'),
                onTap: () {
                  Navigator.pop(context);
                  // 处理拉黑操作
                  _showConfirmationDialog(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('取消'),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  void _showConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认操作'),
          content: const Text('拉黑用户后，您将无法再接收该用户的信息。'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: const Text(
                '取消',
                style: TextStyle(
                    color: Color(0xff1a1a1a),
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),
            ),
            TextButton(
              onPressed: () {
                // context.pop();
                // // 在这里处理拉黑操作
                // // 添加拉黑逻辑
                Navigator.of(context).pop(); // 关闭对话框
                // 在这里添加禁止接收用户信息的逻辑
              },
              child: const Text(
                '拉黑',
                style: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),
            ),
          ],
        );
      },
    );
  }

// 更多按钮点击事件
  void showiOSAlertDialog(BuildContext context) {
    final List<String> reportReasons = [
      '资料造假',
      '恶意骚扰',
      '垃圾广告',
      '色情低俗',
      '诱导欺骗',
    ];

    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: reportReasons.map((reason) {
            return CupertinoActionSheetAction(
              child: Text(
                reason,
                style: const TextStyle(
                    color: Color(0xff333333),
                    fontSize: 15,
                    fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                // Constants.app_showToast("举报已提交");
                // // 执行特定原因的操作
                Navigator.of(context).pop();
                GMAppUtil.gmToast("举报已提交");
              },
            );
          }).toList(),
          cancelButton: CupertinoActionSheetAction(
            child: const Text(
              '取消',
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 15,
              ),
            ),
            onPressed: () {
              // 取消操作
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }
}
